from flask import Blueprint,request,make_response,jsonify,redirect
from utils.bdqpi import bd
from utils.myjwt import myjwt
import json, random, time, requests
from utils.myredis import r
from models.models import *
from utils.md5 import md5

user_blue = Blueprint("userblue",__name__)

from qiniu import Auth
@user_blue.route("/qntoken",methods=["POST"])
# 获取七牛token
def qntoken():
    # 需要填写你的 Access Key 和 Secret Key
    access_key = 'yQBox94ywYZZZfQ5LXKWk6KXc4MMQLcsQdIdBlll'
    secret_key = 'UWf2ZN9Jb21za02YBOXDL4V2hAavLdtBZHhh9U1Z'
    #构建鉴权对象
    q = Auth(access_key, secret_key)
    #要上传的空间
    bucket_name = 'zbajie'
    #生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name)
    return jsonify({"code": 200, "msg":"获取成功","token":token})

@user_blue.route("/bdapi")
# 百度图片识别
def bdapi():
    url = request.args.get("url")
    res = bd.getmes(url)
    name = res[0]['words']
    ID_user = res[1]['words']
    return jsonify({"code": 200, "msg": "获取成功", "mobile": name, "pwd": ID_user})

@user_blue.route("/login",methods=["POST"])
# 注册登录
def login():
    data = json.loads(request.data)
    mobile = data["mobile"]
    pwd = data["pwd"]
    pwds = md5(pwd)
    if not all([mobile,pwd]):
        return jsonify({"code": 400,"msg":"字段不能为空"})
    admin = Admin_user.query.filter_by(mobile=mobile).first()
    if admin:
        if admin.password != pwds:
            return jsonify({"code": 400, "msg": "密码错误"})
        if admin.roleid:
            # 获取页面权限
            menulist,myurl = getMenu(admin.roleid)
            print("页面权限>>>",menulist)
            # 当前角色接口权限
            list = prepare(admin.roleid)
            print("接口权限>>>>>>", list)
            # 加入缓存 检验接口权限
            r.str_add("prepare" + str(admin.id), json.dumps(list))
            data = {"data": {"userid": admin.id, "mobile": admin.mobile,"rolesid":admin.roleid, "exptime": int(time.time())}}
            token = myjwt.jwt_encode(data)
            return jsonify({"code": 200, "msg": "登录成功","token":token,"mobile":admin.mobile,"userid":admin.id,"data":menulist,"myurl":myurl,"roleid":admin.roleid})
        return jsonify({"code":400,"msg":"请联系管理分配权限"})
    user = Admin_user(mobile=mobile,password=pwds)
    db.session.add(user)
    db.session.commit()
    return jsonify({"code": 201, "msg": "注册成功"})

# 页面权限
def getMenu(roleid):
    role = db.session.execute("select res.*,pres.name as pname from role_resource as rr left join resource as res on rr.resourceid=res.id  inner join resource as pres on res.pid=pres.id where rr.roleid=%d and buttonidd=1"%int(roleid))
    if role:
        reslist = []
        ids = []
        myurl = []
        for i in role:
            myurl.append(i['url'])
            # 判断父类是否存在，不存在添加
            if i["pid"] not in ids:
                ids.append(i['pid'])
                reslist.append(
                    {"id": i["pid"], "name": i['pname'], "son": [{"id": i['id'], "name": i['name'], 'url': i['url']}]})
            else:
                # 存在，查找父类，遍历父类用子类的pid对比
                for (index, p) in enumerate(reslist):
                    if i['pid'] == p['id']:
                        # 将子类加到父类下
                        reslist[index]['son'].append({"id": i['id'], "name": i['name'], 'url': i['url']})
        return reslist, myurl

# 接口权限
def prepare(roleid):
    res = db.session.execute("select res.url from role_resource as rr left join resource as res on rr.resourceid=res.id where rr.roleid=%d and res.type=2" % int(
        roleid))
    lst = []
    if res:
        for i in res:
            lst.append(i["url"])
        return lst

# 获取当前审核员的需求
@user_blue.route("/sneed")
def sneed():
    userid = request.args.get("userid")
    need = db.session.query(Need).filter(Need.shr==userid,Need.status==1)
    need1 = db.session.query(Need1).filter(Need1.shr==userid, Need1.status==1)
    need2 = db.session.query(Need2).filter(Need2.shr==userid,Need2.status==1)
    ret = need.union(need1).union(need2).all()
    lst = []
    for i in ret:
        lst.append({
            'code': str(i.code),
            'title': i.title,
            "money": i.money,
            "described": i.described,
            "closeid": i.closeid,
            "userid": i.userid
        })
    return jsonify({"code": 200,"data":lst})

# 审核需求
@user_blue.route("/shneed")
def shneed():
    codes = request.args.get("code")
    code = hash(int(codes)) % 3
    number = "Need"
    if code != 0:
        number = number + str(code)
    number = globals().get(f'{number}')
    res = number.query.filter_by(code=int(codes)).first()
    if res:
        res.status=2
        db.session.add(res)
        db.session.commit()
        return jsonify({"code":200,"msg":"审核成功"})

# 获取全部按钮
@user_blue.route("/getbutton")
def getbutton():
    but = Button.query.filter(Button.id>1).all()
    if but:
        lst = []
        for i in but:
            lst.append({
                "key":i.id,
                "label":i.name
            })
        return jsonify({"code": 200,"data":lst})

# 获取全部资源
@user_blue.route("/getres")
def getres():
    but = Resource.query.filter(Resource.pid!=0).all()
    if but:
        lst = []
        for i in but:
            lst.append({
                "id": i.id,
                "name": i.name,
                "url":i.url
            })
        return jsonify({"code": 200, "data": lst})

# 配置按钮权限
@user_blue.route("/but",methods=["POST"])
def but():
    data = json.loads(request.data)
    roleid = int(data["roleid"])
    resourceid = int(data["resourceid"])
    checkList = data["checkList"]
    # 先删除以前配置的按钮权限
    Role_resource.query.filter(Role_resource.roleid==roleid,Role_resource.resourceid==resourceid,Role_resource.buttonidd!=1).delete()
    db.session.commit()
    for i in checkList:
        # 添加按钮权限
        role = Role_resource(roleid=roleid,resourceid=resourceid,buttonidd=int(i))
        db.session.add(role)
        db.session.commit()
    return jsonify({"code": 200, "msg": "按钮配置成功"})

# 获取页面按钮权限
@user_blue.route("/getbut",methods=["POST"])
def getbut():
    data = json.loads(request.data)
    roleid = int(data["roleid"])
    url = data["url"]
    res = Resource.query.filter_by(url=url).first()
    if res:
        roles = Role_resource.query.filter(Role_resource.roleid==roleid,Role_resource.resourceid==res.id,Role_resource.buttonidd !=1).all()
        lst = []
        for i in list(roles):
            lst.append(i.buttonidd)
        return jsonify({"code":200,"data":lst})

# 退出登录
@user_blue.route("/Exit")
def Exit():
    # 获取头部携带的token
    token = request.headers.get('token')
    key = 'logout'
    # 加入延时队列
    r.sortedset_add(key, token, int(time.time()))
    return jsonify({"code": 200, "msg": '退出成功'})

# 获取没有角色的用户
@user_blue.route("/getuser")
def getuser():
    admin = db.session.execute("select * from admin_user where roleid is null")
    lst = []
    if admin:
        for i in list(admin):
            lst.append({
                "id":i.id,
                "mobile":i.mobile,
                "create_time":str(i.create_time)
            })
    return jsonify({"data":lst})

# 获取所有角色
@user_blue.route("/getroles")
def getroles():
    roles = Roles.query.all()
    if roles:
        lst = []
        for i in list(roles):
            lst.append({
                "id": i.id,
                "name": i.name,
            })
        return jsonify({"data": lst})

# 给用户配角色
@user_blue.route("/setuser",methods=["POST"])
def setuser():
    data = json.loads(request.data)
    id = data["uid"]
    roleid = data["roleid"]
    u = Admin_user.query.filter_by(id=id).first()
    if u:
        u.roleid=roleid
        db.session.add(u)
        db.session.commit()
        return jsonify({"code":200,"msg":"配置成功"})

# 获取所有资源
@user_blue.route("/getresource")
def getresource():
    roleid = request.args.get("roleid")
    res = db.session.execute("select * from resource where pid != 0 and type=1")
    lst = []
    if res:
        for i in list(res):
            lst.append({
                "key": i.id,
                "label": i.name,
            })
    lst1 = []
    res1 = db.session.execute("select * from role_resource where roleid = %d and buttonidd=1"%int(roleid))
    if res1:
        for i in res1:
            lst1.append(i.resourceid,)
    return jsonify({"data": lst,"lst":lst1})

# 角色配置资源
@user_blue.route("/setres",methods=["POST"])
def setres():
    data = json.loads(request.data)
    roleid = data["roleid"]
    resourceid = data["resourceid"]
    Role_resource.query.filter(Role_resource.roleid==roleid,Role_resource.buttonidd==1).delete()
    # db.session.commit()
    for i in resourceid:
        res = Role_resource(roleid=roleid,resourceid=i,buttonidd=1)
        db.session.add(res)
    db.session.commit()
    return jsonify({"code":200,"msg":"配置成功"})

































